package com.datamanage.user.controller;

import com.datamanage.user.dto.UserDTO;
import com.datamanage.user.entity.User;
import com.datamanage.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @PostMapping
    public ResponseEntity<?> createUser(@RequestBody UserDTO userDTO) {
        try {
            User user = userService.createUser(userDTO);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("user", user);
            response.put("message", "用户创建成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id) {
        Optional<User> user = userService.getUserById(id);
        if (user.isPresent()) {
            // 创建简化版的用户信息对象，避免循环引用
            User userDetails = user.get();
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", userDetails.getId());
            userInfo.put("username", userDetails.getUsername());
            userInfo.put("email", userDetails.getEmail());
            userInfo.put("fullName", userDetails.getFullName());
            userInfo.put("phoneNumber", userDetails.getPhoneNumber());
            userInfo.put("isActive", userDetails.getActive());
            userInfo.put("createdAt", userDetails.getCreatedAt());
            userInfo.put("updatedAt", userDetails.getUpdatedAt());
            
            // 只添加用户组的基本信息
            if (userDetails.getGroups() != null) {
                userInfo.put("groups", userDetails.getGroups().stream()
                        .map(group -> {
                            Map<String, Object> groupInfo = new HashMap<>();
                            groupInfo.put("id", group.getId());
                            groupInfo.put("name", group.getName());
                            groupInfo.put("description", group.getDescription());
                            groupInfo.put("createdAt", group.getCreatedAt());
                            groupInfo.put("updatedAt", group.getUpdatedAt());
                            return groupInfo;
                        })
                        .collect(Collectors.toList()));
            }
            
            // 只添加企业的基本信息
            if (userDetails.getCompany() != null) {
                Map<String, Object> companyInfo = new HashMap<>();
                companyInfo.put("id", userDetails.getCompany().getId());
                companyInfo.put("name", userDetails.getCompany().getName());
                companyInfo.put("companyCode", userDetails.getCompany().getCompanyCode());
                userInfo.put("company", companyInfo);
            }
            
            return ResponseEntity.ok(userInfo);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping
    public ResponseEntity<?> getAllUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<User> users = userService.getAllUsers(pageable);
        
        // 创建简化版的用户信息列表，避免循环引用
        Page<Map<String, Object>> simplifiedUsers = users.map(user -> {
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail());
            userInfo.put("fullName", user.getFullName());
            userInfo.put("phoneNumber", user.getPhoneNumber());
            userInfo.put("isActive", user.getActive());
            userInfo.put("createdAt", user.getCreatedAt());
            userInfo.put("updatedAt", user.getUpdatedAt());
            
            // 只添加用户组的基本信息
            if (user.getGroups() != null) {
                userInfo.put("groups", user.getGroups().stream()
                        .map(group -> {
                            Map<String, Object> groupInfo = new HashMap<>();
                            groupInfo.put("id", group.getId());
                            groupInfo.put("name", group.getName());
                            groupInfo.put("description", group.getDescription());
                            groupInfo.put("createdAt", group.getCreatedAt());
                            groupInfo.put("updatedAt", group.getUpdatedAt());
                            return groupInfo;
                        })
                        .collect(Collectors.toList()));
            }
            
            // 只添加企业的基本信息
            if (user.getCompany() != null) {
                Map<String, Object> companyInfo = new HashMap<>();
                companyInfo.put("id", user.getCompany().getId());
                companyInfo.put("name", user.getCompany().getName());
                companyInfo.put("companyCode", user.getCompany().getCompanyCode());
                userInfo.put("company", companyInfo);
            }
            
            return userInfo;
        });
        
        return ResponseEntity.ok(simplifiedUsers);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody UserDTO userDTO) {
        try {
            User user = userService.updateUser(id, userDTO);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("user", user);
            response.put("message", "用户更新成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("message", "用户删除成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @PostMapping("/{userId}/groups/{groupId}")
    public ResponseEntity<?> assignUserToGroup(@PathVariable Long userId, @PathVariable Long groupId) {
        try {
            User user = userService.assignUserToGroup(userId, groupId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("user", user);
            response.put("message", "用户分配到用户组成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @PostMapping("/{userId}/companies/{companyId}")
    public ResponseEntity<?> assignUserToCompany(@PathVariable Long userId, @PathVariable Long companyId) {
        try {
            User user = userService.assignUserToCompany(userId, companyId);
            
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("user", user);
            response.put("message", "用户分配到企业成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<String, Object>();
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}